var meetingroom_search_time;
$(function() {
    $MB.initTpvMeetingElement();
    window.operateEvents = {
        'click .create-meeting': function(e, value, row, index) {
           if(row.licensed){
              openCreateMeetingModal(row.roomId,row.meetingRoomName);
           }else{
              var msg=$MB.i18n('meetingroom.unlicensed');
              $MB.n_danger(msg);
           }
        },
        'click .invit-meeting': function(e, value, row, index) {
           if(row.licensed){
              inviteMeeting(row.roomId);
           }else{
              var msg=$MB.i18n('meetingroom.unlicensed');
              $MB.n_danger(msg);
           }
        },
//        'click .copy-meeting': function(e, value, row, index) {
//           if(row.licensed){
//              copyMeeting(row.roomId);
//           }else{
//              var msg=$MB.i18n('meetingroom.unlicensed');
//              $MB.n_danger(msg);
//           }
//        },
        'click .edit-meetingroom': function(e, value, row, index) {
            updateMeetingRoom(row.hardwareKey);
        },
        'click .action-reset': function(e, value, row, index) {
            if(row.loggedin){
               sendCmdToPd(row.hardwareKey,"Reboot","");
            }
        },
        'click .action-screenshot': function(e, value, row, index) {
            if(row.loggedin){
               sendCmdToPd(row.hardwareKey,"ScreenShot","");
            }
        },
//        'click .action-volume': function(e, value, row, index) {
//           if(row.loggedin){
//              openVolumeModal(row.hardwareKey);
//            }
//        },
        //Tpv zhongxiang.huang 20181228, add meetingroom upgrade
        'click .action-maxusers-upgrade': function(e, value, row, index) {
        	maxUsersAllowedUpgrade(row.hardwareKey);
        }
    };

    createMeetingRoomGroupTree();
    var unselectMsg=$MB.i18n('meetingroom.unselect');
    $('#deleteGroup').click(function(){
        var ref = $("#meetingRoomGroup").jstree(true);
        var sel = ref.get_selected();
        if(sel==0||sel===""){
           $MB.n_danger(unselectMsg);
           return;
        }else{
           ref.delete_node(sel);
        }
    });

    $('#renameGroup').click(function(){
        var ref = $("#meetingRoomGroup").jstree(true);
        var sel = ref.get_selected();
        if(sel==0||sel===""){
           $MB.n_danger(unselectMsg);
           return;
        }else{
           ref.edit(sel);
        }
    });

    $('#createGroup').click(function(){
        var ref = $("#meetingRoomGroup").jstree(true);
        var sel = ref.get_selected();
        console.log(sel);
        if(sel.length==0){
           $MB.n_danger(unselectMsg);
           return;
        }else{
           sel = sel[0];
           var rootNode=ref.get_node(0);
           var name=$MB.i18n('meetingroom.unname');
           var userId=$("#currUserId").val();
//           console.log("userId:"+userId);
          if(sel==0){
             var deptId=$('#currDeptId').val();
             console.log("deptId:"+deptId);
             if(deptId==1){
                if(rootNode.children_d.length==0){
                   name=name+"_"+userId+(parseInt(sel, 10)+userId+1);
                }else{
                  var max = Math.max.apply(null,rootNode.children_d);
                  name=name+"_"+userId+(parseInt(max, 10)+1);
                }
             }else{
                  $MB.n_danger(unselectMsg);
                  return;
             }
          }else{
             if(rootNode.children_d.length==0){
                name=name+"_"+userId+(parseInt(sel, 10)+1);
             }else{
                var max = Math.max.apply(null,rootNode.children_d);
                name=name+"_"+userId+(parseInt(max, 10)+1);
             }
          }
           $("#meetingRoomGroup").jstree('create_node',sel, { type : "default", text : name }, "last",function (new_node) {});
        }

    });

    initMeetingRoomTable();

//    $("#meeting-detail .btn-close").click(function() {
//        $MB.closeAndRestModal("meeting-detail");
//    });
//    $("#meeting-detail").find("#meeting-detail-join-attendee").click(function() {
//        joinMeeting(false);
//    });
//    $("#meeting-detail").find("#meeting-detail-join-moderator").click(function() {
//        joinMeeting(true);
//    });

//    $("#meeting-detail").find("#meeting-detail-end").click(function() {
//        endMeeting();
//    });

    $("#volume-operation .btn-close").click(function() {
        $MB.closeAndRestModal("volume-operation");
    });

    $(this).find(".meetingroom-table-form input[type=text]").on("keyup",function(){
                if (meetingroom_search_time) {
                   clearTimeout(meetingroom_search_time);
                }
                meetingroom_search_time = setTimeout(function() {
                   search();
                },300);
    });

    $(this).find(".meetingroom-table-form select").on("change", search);

    $(this).find(".dataTables_wrapper input[type=radio]").on("change",  search);

    //meetingroom.delmsg=请勾选需要删除的会议室
    //meetingroom.deltxt=确定删除选中会议室?
    //meetingroom.confirm=确定
    //meetingroom.authomsg=请勾选需要授权的会议室
    //meetingroom.deauthomsg=请勾选需要取消授权的会议室
    //meetingroom.authortxt=确定授权选中会议室?
    //meetingroom.deauthortxt=确定取消授权选中会议室?
});

function initMeetingRoomTable(){
    var $meetingroomTableForm = $(".meetingroom-table-form");
    var meetingroomSettings = {
        url: ctx + "meetingroom/list",
        pageSize: 10,
        pageList: [5, 10, 25, 50],
        clickToSelect: false,
        queryParams: function(params) {
            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                name: $meetingroomTableForm.find("input[name='name']").val().trim(),
                model: $meetingroomTableForm.find("input[name='model']").val().trim(),
                mac: $meetingroomTableForm.find("input[name='mac']").val().trim(),
                licensed: $meetingroomTableForm.find("select[name='licensed']").val(),
                valid: $meetingroomTableForm.find("select[name='valid']").val(),
                state: $('#filter_state input:radio:checked').val(),
                groupIds: $('#groupIds').val(),
            };
        },
        onLoadSuccess:function(data){
            $("#freeCount").html(" (" + data.free + "/" + data.all+")");
            $("#usedCount").html(" (" + (data.all - data.free) + "/" + data.all+")");
        },
        columns: [{
            checkbox: true,
            width:'2%',
        }, {
            field: 'roomId',
            visible: false
        }, {
            field: 'displayId',
            visible: false
        }, {
            field: 'meetingRoomName',
            title: $MB.i18n('meetingroom.name'),
            width:'22.5%',//Tpv zhongxiang.huang 20181228, modify 24% to 22.5%
            events: operateEvents,
            formatter: function(value, row, index) {
                var src="img/vc/meetingroom_nor.png";
                if(row.loggedin){
                   src="img/vc/meetingroom_hl.png"
                }
                var info = Handlebars.compile($("#meetingroom-info").html());
                var cpuUsed=(row.cpuUsed == null||row.cpuUsed == "")?"N/A":row.cpuUsed;
                var ramUsed = (row.ramUsed == null||row.ramUsed == "")?"N/A":((Number(row.ramTotal)-Number(row.ramUsed))/1024/1024).toFixed(2);
                var ramTotal = (row.ramTotal == null||row.ramTotal == "")?"N/A":(row.ramTotal/1024/1024).toFixed(2);
                var model= (row.modelName == null||row.modelName == "")? "N/A":row.modelName;
                var retHtml= info({
                                        name: value,
                                        model: model,
                                        displayimg:src,
                                        isonline: row.loggedin,
                                        cpu: cpuUsed+"%",
                                        ram: ramUsed+' GB/'+ramTotal+' GB'
                });
                return [retHtml].join("");
            }
        }, {
        	//Tpv zhongxiang.huang 20181228, add meetingroom upgrade----start
            field: 'maxUsersAllowed',
            title: $MB.i18n('meetingroom.maxusers'),
            width:'8.5%',  //5.5% to 8.5%
            events: operateEvents,
            formatter: function(value, row, index){
            	var upg=$MB.i18n('upgrade');
            	var info = Handlebars.compile($("#meetingroom-max-users-allowed").html());
            	var retHtml= info({
            		maxUsersAllowed: value,
            		upgrade: upg
				});
				return [retHtml].join("");
            }
        	//Tpv zhongxiang.huang 20181228, add meetingroom upgrade----end
        }, {
            field: 'licensed',
            title: $MB.i18n('meetingroom.authorise'),
            width: '4%',
            align: 'center',
            formatter: function(value, row, index) {
                if (value) return ['<span class="zmdi zmdi-check zmdi-hc-lg"></span>'].join("");
                else return ['<span class="zmdi zmdi-close zmdi-hc-lg"></span>'].join("");
            }
        }, {
            field: 'hardwareKey',
            title: $MB.i18n('meetingroom.maxusers'),
            visible: false
        }, {
            field: 'expireTime',
            title: $MB.i18n('meetingroom.expried'),
             width:'6%'
        }, {
            field: 'valid',
            title: $MB.i18n('meetingroom.valid'),
            width: '6%',
            align: 'center',
            formatter: function(value, row, index) {
    //                console.log(value);
                if (value) return ['<span class="zmdi zmdi-check zmdi-hc-lg"></span>'].join("");
                else return ['<span class="zmdi zmdi-close zmdi-hc-lg"></span>'].join("");
            }
        }
    //        , {
    //            field: 'loggedin',
    //            title: '已登陆?',
    //            width: '20px',
    //            formatter: function(value, row, index) {
    //                if (value) return '是';
    //                else return '否';
    //            }
    //        }
        , {
            field: 'lastaccessedTime',
            title:  $MB.i18n('meetingroom.lasttime'),
             width:'10%'
        },{
              field: 'usageCount',
              title: $MB.i18n('meetingroom.usagecount'),
              width:'6%'
          }
        , {
            field: 'meetingRoomState',
            title: $MB.i18n('meetingroom.state'),
            width:'6%',
             formatter: function(value, row, index) {
                 if (value) return $MB.i18n('meetingroom.using');
                 else return $MB.i18n('meetingroom.idle');;
             }
        },{
               field: 'location',
               width: '5%',
               class: 'text-truncate',
               title: $MB.i18n('meetingroom.location')
        }, {
             title: $MB.i18n('meetingroom.remote'),
             width: '12%',
             events: operateEvents,
             formatter: function(value, row, index) {
                 var box = Handlebars.compile($("#remote-action-box").html());
                 var retHtml= box({
                        resetimg: row.loggedin? "img/vc/icon_restart.png":"img/vc/icon_restart_disable1.png",
                        screenshotimg: row.loggedin? "img/vc/icon_screenshot.png":"img/vc/icon_screenshot_disable1.png",
                        volumeimg: row.loggedin? "img/vc/icon_volume.png":"img/vc/icon_volume_disable1.png",
                        ip: row.loggedin? row.ipAddress:"N/A",
                        mac:row.macAddress,
                        version: row.clientVersion
                 });
                 return [retHtml].join("");
              }
           }
        , {
            title: $MB.i18n('meetingroom.operate'),
            events: operateEvents,
            width: '11%',
            formatter: function(value, row, index) {
                 var box = Handlebars.compile($("#operation-box").html());
                 var retHtml=box();
                 return [retHtml].join("");
            }
        }]
    };

    $MB.initTable('meetingRoomTable', meetingroomSettings);
}

function refresh() {
    $("#filter_state").find(".active").removeClass("active");
    $("#filter_state").find("input[type='radio']").removeAttr("checked");
    $(".meetingroom-table-form")[0].reset();
    $MB.refreshTable('meetingRoomTable');
}

function search() {
    $MB.refreshTable('meetingRoomTable');
}

function deleteMeetingRooms() {
    var selected = $("#meetingRoomTable").bootstrapTable('getSelections');
    var selected_length = selected.length;
    var contain = false;
    if (!selected_length) {
        $MB.n_warning($MB.i18n('meetingroom.delmsg'));
        return;
    }
    var ids = "";
    for (var i = 0; i < selected_length; i++) {
        ids += selected[i].hardwareKey;
        if (i !== (selected_length - 1)) ids += ",";
    }

    $MB.confirm({
        text: $MB.i18n('meetingroom.deltxt'),
        confirmButtonText: $MB.i18n('meetingroom.confirm')
    }, function() {
        $.post(ctx + 'meetingroom/delete', { "ids": ids }, function(r) {
            if (r.code === 0) {
                $MB.n_success(r.msg);
                refresh();
            } else {
                $MB.n_danger(r.msg);
            }
        });
    });
}

function authorizeMeetingRoom() {
    var selected = $("#meetingRoomTable").bootstrapTable('getSelections');
    var selected_length = selected.length;
    var contain = false;
    if (!selected_length) {
        // mod by Ting.Wong 2018-12-27 10:05 start
        $MB.n_warning($MB.i18n('meetingroom.authomsg'));
        // mod by Ting.Wong 2018-12-27 10:05 end
        return;
    }
    var ids = "";
    for (var i = 0; i < selected_length; i++) {
        ids += selected[i].roomId;
        if (i !== (selected_length - 1)) ids += ",";
        if (selected[i].licensed) contain = true;
    }
    if (contain) {
        // chaohung , 20190114
    	//$MB.n_warning('包含已授权会议室，无法后续操作！');
        $MB.n_warning($MB.i18n('meetingroom.war1'));
        return;
    }

    $MB.confirm({
        text: $MB.i18n('meetingroom.authortxt'),
        confirmButtonText: $MB.i18n('meetingroom.confirm')
    }, function() {
        $.post(ctx + 'meetingroom/authorize', { "ids": ids }, function(r) {
            if (r.code === 0) {
                $MB.n_success(r.msg);
                refresh();
            } else {
                $MB.n_danger(r.msg);
            }
        });
    });
}

function deAuthorizeMeetingRoom() {
    var selected = $("#meetingRoomTable").bootstrapTable('getSelections');
    var selected_length = selected.length;
    var contain = false;
    if (!selected_length) {
        $MB.n_warning($MB.i18n('meetingroom.deauthomsg'));
        return;
    }
    var ids = "";
    for (var i = 0; i < selected_length; i++) {
        ids += selected[i].roomId;
        if (i !== (selected_length - 1)) ids += ",";
        if (!selected[i].licensed) contain = true;
    }
    if (contain) {
    	// chaohung , 20190114
        //$MB.n_warning('包含未授权会议室，无法后续操作！');
    	$MB.n_warning($MB.i18n('meetingroom.war2'));    	    
        return;
    }

    $MB.confirm({
        text: $MB.i18n('meetingroom.deauthortxt'),
        confirmButtonText: $MB.i18n('meetingroom.confirm')
    }, function() {
        $.post(ctx + 'meetingroom/deauthorize', { "ids": ids }, function(r) {
            if (r.code === 0) {
                $MB.n_success(r.msg);
                refresh();
            } else {
                $MB.n_danger(r.msg);
            }
        });
    });
}

function updateMeetingRoom(hardwareKey) {
    var hardwareKey = hardwareKey;
    $.post(ctx + "meetingroom/getMeetingRoom", { "hardwareKey": hardwareKey }, function(r) {
        if (r.code === 0) {
            var $form = $('#meetingroom-edit');
            $form.modal();
            console.log(r.msg);
            var meetingroom = r.msg;
            //            $form.find(".user_password").hide();
            //$("#meetingroom-edit-modal-title").html('编辑会议室');
            $form.find("input[name='meetingRoomName']").val(meetingroom.meetingRoomName);
            $form.find("input[name='oldmeetingRoomName']").val(meetingroom.meetingRoomName);
            $form.find("input[name='roomId']").val(meetingroom.roomId);
            $form.find("input[name='hardwareKey']").val(meetingroom.hardwareKey);
            $form.find("input[name='location']").val(meetingroom.location);
            $form.find("input[name='maxUsersAllowed']").val(meetingroom.maxUsersAllowed);
            // chaohung , 20190124 , fix space error
            var real = (meetingroom.setexcessspace)/1024/1024/1024 ;            
            $form.find("input[name='setexcessspace']").val(meetingroom.setexcessspace);
            $form.find("input[name='setexcessspaceshow']").val(real);
            // chaohung , 20190122 , get used space 
            // chaohung , 20190124 , fix used space from byte to GB
            var usedspace = (meetingroom.usedspace)/1024/1024/1024 ;
            var usedspacestring = usedspace.toFixed(2);                                  
            $form.find("input[name='usedspace']").val(usedspacestring);
            
            
            var expireTimeEle=$form.find("input[name='expireTime']");
            expireTimeEle.val(meetingroom.expireTime);
            $MB.calenders(expireTimeEle,false,false);
            var $status = $form.find("input[name='licensed']");
            if (meetingroom.licensed) {
                $status.prop("checked", true);
                // chaohung , 20190114
                //$status.parent().next().html('已授权');
                $status.parent().next().html($MB.i18n('meetingroom.licensetext'));                
            } else {
                $status.prop("checked", false);
                // chaohung , 20190114
                //$status.parent().next().html('未授权');
                $status.parent().next().html($MB.i18n('meetingroom.unlicensetext'));
            }
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function openCreateMeetingModal(meetingRoomId,meetingRoomName) {
    var meetingRoomId = meetingRoomId;
    var $form = $('#meeting-add');
    $form.modal();
//    $form.find('#repeat-off').iCheck('check');
    $form.find("#meeting-add-form").attr("action", "add");
    $form.find("#select-room").hide();
    $form.find("#is-room").css('display','inline');
    $form.find("input[name='meetingroomName']").val(meetingRoomName);
    $form.find("input[name='meetingroomId']").val(meetingRoomId);
}

function inviteMeeting(roomId) {
    $.get(ctx + "meetingroom/getMeeting/" + roomId, function(r) {
        if (r.code == 0) {
            console.log(r.msg);
            var meetingId = r.msg.id;
                $.get(ctx + "meeting/detail/" + meetingId, function(r) {
                if(r.code == 0) {
                    var detail = $('#meeting-detail');

                    $(detail).find("#meeting-detail-reopen").hide();
                    $(detail).find("#meeting-detail-reschedule").hide();

                    var meeting = r.msg;
                    $("#meeting-detail-name").empty();
                    $("#meeting-detail-name").append(meeting.name);


                    //Tpv zhongxiang.huang 20181226,add for wechart invite
                    var wecharInvite = $('#meeting-wechart-invite');

                    $(detail).attr("meeting-id", meetingId);
                    $(detail).attr('user-id', meeting.currentUserId);
                    $(detail).attr('username', meeting.currentUsername);

                    var topic = $(detail).find("#meeting-detail-topic");
                    topic.empty();
                    topic.append(meeting.topic);

                    var content = $(detail).find("#meeting-detail-content");
		    
                    //Tpv zhongxiang.huang 20181229 modify-----start
                    var meetingContent = meeting.content;
                    var re = new RegExp("\n", "g");// 匹配所有的\n，g表示全部global
                    content.empty();
                    content.html(meetingContent.replace(re, "<br/>")).show();// html中解析换行用<br/>
//                    content.append(meeting.content);
                    var meetingOriginator = $(detail).find("#meeting-detail-originator");
                    meetingOriginator.empty();
                    meetingOriginator.append(meeting.username);
                    //Tpv zhongxiang.huang 20181229 modify-----end

                    var meetingTime = $(detail).find("#meeting-detail-time");
                    meetingTime.empty();
                    meetingTime.append($MB.formatDate(meeting.start, meeting.end));

                    var inviteId = $(detail).find("#meeting-detail-id");
                    inviteId.empty();
                    inviteId.append(meeting.meetingId);

                    var inviteId = $(detail).find("#meeting-detail-id");
                    inviteId.empty();
                    inviteId.append(meeting.meetingId);

                    var meetingPassword = $(detail).find("#meeting-detail-password");
                    meetingPassword.empty();
                    meetingPassword.append(meeting.password);

                    var inviteUrl = $(detail).find("#meeting-detail-url");
                    inviteUrl.empty();
                    inviteUrl.append(meeting.url);
                    inviteUrl.attr('href', meeting.url);

                    var members = $(detail).find("#meeting-detail-members");
                    members.empty();
                    if(meeting.members.length > 0) {
                        members.append(meeting.members[0].nick);
                        for(var i=1; i<meeting.members.length; i++) {
                            members.append(',');
                            members.append(meeting.members[i].nick);
                        }
                    }
                    if(meeting.isEnd){
                       $(detail).find("#meeting-detail-end").attr("disabled",true);
                    }else{
                       $(detail).find("#meeting-detail-end").attr("disabled",false);
                    }
//                    $('#copyVal').val(meeting.inviteUrl);
                    $(detail).find(".copyBtn").attr('data-clipboard-text',meeting.inviteUrl);
                    $(detail).find("#meeting-detail-qrcode").attr("src", "data:image/png;base64," + meeting.qrcode);
                    //Tpv zhongxiang.huang 20181226,add for wechart invite
                    //$(wecharInvite).find("#meeting-wechart-invite-qrcode").attr("src", "data:image/png;base64," + meeting.inviteQrcode);
                    var clipboard = new ClipboardJS('.copyBtn', {
                        container: document.getElementById('meeting-detail')
                    });
                    $(detail).on("shown.bs.modal", function() {
                          clipboard.on('success', function(e) {
                               $MB.n_success($MB.i18n('meeting.copy.successtxt'));
                          });
                          clipboard.on('error', function(e) {
                              $MB.n_danger($MB.i18n('meeting.copy.failtxt'));
                          });
                    });
                    $(detail).on('hide.bs.modal', function () {
                        if(clipboard){
                           clipboard.destroy();
                        }
                    });
                    $(detail).modal();
                } else {
                    $MB.n_danger(r.msg);
                }
            });
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function sendCmdToPd(hkey,cmd,val){
   $.post(ctx + "meetingroom/action", { "hardwareKey": hkey,"cmd":cmd,"value":val }, function(r) {
         if (r.code === 0) {
             $MB.n_success(r.msg);
         } else {
             $MB.n_danger(r.msg);
         }
   });
 }

 function openVolumeModal(hardwareKey) {
         var $form = $('#volume-operation');
         $form.modal();
         $form.find("#hardwareKey").val(hardwareKey);
 }

 function changeSpeed() {
     var value = $('#volume').val();
     var valStr = value + "% 100%";
     $('#volume').css({
       "background-size": valStr
     });
}

function createMeetingRoomGroupTree(){
	$.post(ctx + "meetingroom/tree", {}, function (r) {
        if (r.code === 0) {
            var data = r.msg;
            console.log(data);
            $('#meetingRoomGroup').jstree({
                "core": {
                    'data': data,
                    'check_callback':true,
                    'force_text' : true,
                    "themes" : {
                        "dots" : false,
                        "ellipsis":true
                    }
                },
                "plugins" : ["themes","ui"]
            }).on('ready.jstree', function(e, data){
                 var inst = data.instance;
                 inst.open_all();
                 //// 隐藏根节点 http://stackoverflow.com/questions/10429876/how-to-hide-root-node-from-jstree
//                 console.log($("#0_anchor").prev());
//                 $("#0_anchor").prev().css("display", "none");
//                 $("#0_anchor").css("display", "none");
//                 $("li#0").css("position", "relative");
//                 $("li#0").css("top", "-20px");
//                 $("li#0").css("left", "-20px");
//                 $(".jstree-last .jstree-icon").first().hide();
            }).on("select_node.jstree", function (e, data) {
                  var inst = data.instance;
                  if(data.node!=undefined){
                      $("#select-title").empty();
                      $("#select-title").append(data.node.text);
                      inst.select_node(data.selected);
                      inst.select_node(data.selected);
                      var selectGroupIds= [];
//                      if(data.selected != -1){
                          selectGroupIds = selectGroupIds.concat(data.node.children_d);
                          selectGroupIds = selectGroupIds.concat(data.selected);
                          var deptId=$('#currDeptId').val();
                          if(deptId!=1){
                             if(data.selected==0){
                                var index = selectGroupIds.indexOf("0");
                                selectGroupIds.splice(index,1);
                             }
                          }
//                          console.log(selectGroupIds);
                          $("#groupIds").val(selectGroupIds.join(","));
                          $MB.refreshTable('meetingRoomTable');
//                      }
                  }
                  inst.open_node(data.selected);
            }).on('delete_node.jstree', function (e, data){
                 console.log(data);
                 var groupIds= new Array();
                 groupIds = groupIds.concat(data.node.children_d);
                 groupIds = groupIds.concat(data.node.id);
                 console.log(groupIds);
                 $.post(ctx + 'meetingroom/delgroup', { "ids": groupIds.join(","),"parentId":data.node.parent=="#"?"0":data.node.parent}, function(r) {
                     if (r.code === 0) {
                         $MB.n_success(r.msg);
                         data.instance.select_node(data.node.parent);
//                         $('#dialog-group-tree').jstree(true).refresh();
                         //data.instance.refresh();
                     } else {
                         $MB.n_danger(r.msg);
                         data.instance.refresh();
                     }
                 });
            }).on("rename_node.jstree", function(e, data){
                 console.log(data);
                 $.post(ctx + 'meetingroom/renamegroup', { "groupId": parseInt(data.node.id, 10),"groupName":data.text}, function(r) {
                     if (r.code === 0) {
                         $MB.n_success(r.msg);
                         //data.instance.refresh();
//                         $('#dialog-group-tree').jstree(true).refresh();
                     } else {
                         $MB.n_danger(r.msg);
                         data.instance.refresh();
                     }
                 });
            }).on('create_node.jstree', function (e, data) {
//                  console.log('create_node:');
//                  console.log(data);
                $.post(ctx + 'meetingroom/creategroup', {"groupName":data.node.text,"parentId":data.node.parent=="#"?"0":data.node.parent}, function(r) {
                     if (r.code === 0) {
                         data.instance.set_id(data.node, r.msg.id);
                         $MB.refreshTable('meetingRoomTable');
                         setTimeout(function(){
                             data.instance.open_node(data.node.parent);
                             data.instance.deselect_all();
                             data.instance.edit(data.node);
                             data.instance.select_node(data.node.id);
//                             $('#dialog-group-tree').jstree(true).refresh();
                         }, 0);
                     } else {
                         $MB.n_danger(r.msg);
                         data.instance.refresh();
                     }
                });
            });
        } else {
            $MB.n_danger(r.msg);
        }
    })
}

function openMoveToModal() {
    var selected = $("#meetingRoomTable").bootstrapTable('getSelections');
    var selected_length = selected.length;
    if (!selected_length) {
        $MB.n_warning($MB.i18n('meetingroom.delmsg'));
        return;
    }
    var ids = "";
    for (var i = 0; i < selected_length; i++) {
        ids += selected[i].roomId;
        if (i !== (selected_length - 1)) ids += ",";
    }
    var $form = $('#meetingroom-move');

    initModalGroupTree();
    $form.modal();
    $form.find("#ids").val(ids);
}

function copyMeeting(roomId) {
    $.get(ctx + "meetingroom/getMeeting/" + roomId, function(r) {
        if (r.code == 0) {
            var meetingId = r.msg.id;
            openInviteTxt(meetingId);
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function copyMeetingTxt(e){
      $MB.closeModal(e.attr('id'));
      var meetingId=e.attr('meeting-id');
      openInviteTxt(meetingId);
}

/*******
 * Tpv zhongxiang.huang 20181226--add by zhongxiang.huang,meeting update----
 * *******/
function maxUsersAllowedUpgrade(hardwareKey){
	openMeetingroomUpgradeGuide(hardwareKey);
}

function initModalGroupTree(){
    $('#dialog-group-tree').data('jstree', false).empty();
	$.post(ctx + "meetingroom/tree", {}, function (r) {
        if (r.code === 0) {
            var data = r.msg;
            $('#dialog-group-tree').jstree({
                "core": {
                    'data': data.children,
                    'check_callback':true,
                    'force_text' : true,
                    "themes" : {
                        "dots" : false,
                        "ellipsis":true
                    }
                },
                "state": {
                    "disabled": true
                },
                "plugins" : ["themes","ui","unique"]
            }).on('ready.jstree', function(e, data){
                 var inst = data.instance;
                 inst.open_all();
            });
        } else {
            $MB.n_danger(r.msg);
        }
    })
}

function endMeeting(){
   $.post(ctx + "meeting/end", { "meetingId": $("#meeting-detail").attr("meeting-id")}, function(r) {
        if (r.code === 0) {
            $MB.n_success(r.msg);
        } else {
            $MB.n_danger(r.msg);
        }
   });
}

